<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/8/5
 * Time: 下午4:37
 */
namespace app\api\controller\v1;

use app\api\controller\Common;
use think\Controller;
use app\common\lib\exception\ApiException;
use app\common\lib\Aes;
use app\common\lib\IAuth;

class Login extends Common {

    public function save(){
      if (!request()->isPost()) {
        return show(config('code.error'),'无权限','',403);
      }

      $param = input('param.');
      if (empty($param['phone'])) {
        return show(config('code.error'),'手机不合法','',404);
      }
      if (empty($param['code']) && empty($param['password'])) {
        return show(config('code.error'),'验证码或密码不合法','',404);
      }
      //validate 严格校验  自己做

      if (!empty($param['code'])) {
        if ($param['code'] != 123456) {
          return show(config('code.error'),'验证码正确','',404);
        }
      }
      //查询手机号是否存在
      try {
        $user = model('User')->get(['phone'=>$param['phone']]);
      } catch (\Exception $e) {
        return new ApiException('error', 400);
      }
      $token = IAuth::setAppLoginToken($param['phone']);

      if (!$user) {
        if (!empty($param['code'])) {
            //第一次登录注册数据
            $data = [
              'token' => $token,
              'time_out' => strtotime("+".config("app.login_time_out_day")."days"),
              'username' => 'tao粉-'.$param['phone'],
              'status'  => 1,
              'phone' => $param['phone'],
            ];
          try {
            $id = model('User')->add($data);
          } catch (\Exception $e) {
            return new ApiException('error', 400);
          }
        }else{
           return show(config('code.error'),'用户不存在','',404);
        }

      }else{
        if ($user->status != 1) {
          return show(config('code.error'),'用户不存在','',404);
        }

        if (!empty($param['password'])) {
          //判定用户的密码 和 数据库是否相同
          if (IAuth::setPassword($param['password']) != $user->password) {
            return show(config('code.error'),'error','',404);
          }
        }
           //更新用户token
           $data = [
            'token' => $token,
            'time_out' => strtotime("+".config("app.login_time_out_day")."days"),
          ];
        try {
          $id = model('User')->editUserData(['id'=>$user['id']],$data);
        } catch (\Exception $e) {
          return new ApiException('error', 400);
        }
      }

      $obj = new Aes();
      if ($id) {
        $result = [
            'token' => $obj->encrypt($token."||".$id),
        ];

        return show(config('code.success'),'登录成功',$result,200);
      }else{
        return show(config('code.error'),'error','',404);
      }
    }

}